<?php
class LinksController extends AppController {

	var $name = 'Links';

	var $components=array('RequestHandler');
	
	var $paginate=array(
		'Link'=>array(
			'contain' => array('Category'=>array('id','name'),'Category.Parent'=>array('id','name'), 'User'=>array()),
			'order'=>array('Link.id'=>'DESC'),
			'limit' => 20,
		),'Comment'=>array(
			'fields'=>array('id','created','votes','karma','content'),				
			'contain'=>array(
				'User'=>array('login','karma')				
			),
			'order'=>array('Comment.id'=>'DESC'),
			'limit' => 20
		)
	);

	function index($cat_id=null) {
		//index are the published stories	
		$this->_setIndex('published',$cat_id);	
	}
		
	function shakeit($cat_id=null) {
		$this->_setIndex('queued',$cat_id);
	}

	function view($id = null) {
		$this->helpers[]='Ajax';

		if (!$id) {
			$this->Session->setFlash(__('Invalid link', true));
			$this->redirect(array('action' => 'index'));
		}
						
		$this->Link->contain(array('Category'=>array('id','name'),'Category.Parent'=>array('id','name'), 'User'));
		$link=$this->Link->read(null, $id);
		
		if($link['isVotable']=$this->Link->isVotable($link)){
			$link['voteValue']=$this->Link->Vote->getLinkVoteValue($link['Link']['id'],$this->Auth->user('id'));
		}
		
		$this->paginate['Comment']['conditions']['Comment.link_id']=$id;
		$this->paginate['Comment']['conditions']['Comment.parent']=0;
		$comments=$this->paginate($this->Link->Comment);
		
		$this->set(compact('link', 'comments'));
	}
	
	function addcomment($link_id){
		$this->helpers[]='Ajax';
				
		$this->autoRender = false;
		$this->disableCache();
		
		if (!$this->RequestHandler->isAjax()||!$link_id) {
	    	exit;	
		}
	    				
		if($error=$this->Link->User->cantPostComment($this->Session->read('Auth.User.id'))){
  			$this->set('error',$error);	
  		}else if (!empty($this->data)) {
   			$this->Link->Comment->create();
   			$this->Link->Comment->set(array('content'=>$this->data['Comment']['content'],'link_id'=>$link_id,'user_id'=>$this->Session->read('Auth.User.id')));
   			
   			if ($this->Link->Comment->save()) {
   				$this->set('message',__('Comment saved succesful',true));
    			$this->render('/elements/success');
   				return;
   			}
  		}
  			
  		$this->set('link_id',$link_id);
  		$this->render('/elements/commentform');
        
	}

	function add() {
		try{
			$this->Link->User->id=$this->Auth->user('id');
			$this->Link->User->checkCanPostLinks();
						
			$paso=isset($this->data['Link']['paso']) ? $this->data['Link']['paso'] : 1;
			$this->set('paso',$paso);
		
			if (!empty($this->data)) {
				if($paso==1){
					$this->_doAddStep1();
				}elseif ($paso==2){
					$this->_doAddStep2();
				}
			}
				
			$this->set('warning',isset($this->Link->warning) ? $this->Link->warning : false);
		}catch (AddLinkException $linkException){
			$this->set('message',$linkException->getMessage());
			$this->render('/elements/error');
		}
	}
	
	function doVote(){
		if(empty($this->params['form'])) exit;
		$link_id=$this->params['form']['id'];
		
		if($link_id){
			if($this->Session->check('Auth.User.id')){
				$user=array(
					'id'=>$this->Auth->user('id'),
					'karma'=>round($this->Auth->user('karma'))
				);
			}else{
				$user=array(
					'id'=>0,
					'karma'=>round(Configure::read('Monky.Anon.karma'))
				);
			}
			
			$user['vote']=$this->params['form']['value'];
			
			try{
				$this->set('vote_result',$this->Link->vote($link_id,$user));
			}catch(ErrorVoteException $exception){
				$this->set('vote_result',array('error'=>$exception->getMessage()));
			}
		}
				
		$this->layout = 'json';
		$this->render('json/vote');
	}
	

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid link', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Link->save($this->data)) {
				$this->Session->setFlash(__('The link has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The link could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Link->read(null, $id);
		}
		$users = $this->Link->User->find('list');
		$blogs = $this->Link->Blog->find('list');
		$categories = $this->Link->Category->find('list');
		$this->set(compact('users', 'blogs', 'categories'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for link', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Link->delete($id)) {
			$this->Session->setFlash(__('Link deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Link was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function beforeFilter(){
		parent::beforeFilter();
		
		$this->helpers[]='Text';
		$this->helpers[]='Time';
		
		$this->Auth->deny('add');
	}	
	
	function _setIndex($link_status,$cat_id=null){
		
		if($cat_id!=null){ 
			$this->paginate['Link']['conditions']['OR']=array('Category.parent'=>$cat_id,'Category.id'=>$cat_id);
		}
		
		$this->paginate['Link']['conditions']['status']=$link_status;
				
		$this->set('links', $this->paginateLink());	
	}
	
	function paginateLink(){
		$paginate=parent::paginate($this->Link);
			
		
		foreach ($paginate as $id=>$link){
			if($paginate[$id]['isVotable']=$this->Link->isVotable($link)){
				$paginate[$id]['voteValue']=$this->Link->Vote->getLinkVoteValue($link['Link']['id'],$this->Auth->user('id'));
			}
		}
		
		return $paginate;
	}	
	
	function _doAddStep1(){
		
		$this->Link->setValidateStep1();
		$this->Link->create($this->data);
		
		
		if($this->Link->validates()){
			
			if(!$this->Link->data['Link']['blog_id']){
				$this->data['Link']['blog_id']=$this->Link->Blog->getBlogData($this->Link->pageObj->url,$this->Link->pageObj->html);
			}
			
			$serialize=serialize(array(
				'blog_id'=>$this->data['Link']['blog_id'],
				'link_title'=>$this->Link->pageObj->title,
				'link_content'=>$this->Link->pageObj->description,
				'link_images'=>$this->Link->pageObj->images,
				'type'=>$this->data['Link']['type']
			));
						
			if(!isset($this->Link->data['Link']['title'])||$this->Link->data['Link']['title']=='')$this->Link->data['Link']['title']=$this->Link->pageObj->title;
			if(!isset($this->Link->data['Link']['content'])||$this->Link->data['Link']['content']=='')$this->Link->data['Link']['content']=$this->Link->pageObj->description;
						
			$this->Link->data['Link']=array_merge(array(
				'link_title'=>$this->Link->pageObj->title,
				'link_content'=>$this->Link->pageObj->description,
				'link_images'=>$this->Link->pageObj->images,
				'obj'=>$serialize,
				'hash'=>Security::hash($serialize,'md5',true)
			),$this->Link->data['Link']);
			$this->set('paso',2);
		}
		
				
		$this->Link->data['Link']['type']=$this->data['Link']['type'];
		
		$this->data=array_merge($this->data,$this->Link->data);
		
	}
	
	function _doAddStep2(){	
		if(Security::hash($this->data['Link']['obj'],'md5',true)!=$this->data['Link']['hash']){
			$this->Session->setFlash(__('A internal security flag has been trigger, plase submit the link again', true));
			$this->redirect(array('controller'=>'links','action'=>'add'));
		}
				
		$l=unserialize($this->data['Link']['obj']);
		
		
		
		$this->data['Link']=am($this->data['Link'],$l);
								
		$this->data['Link']=am($this->data['Link'],array(
			'title'=>superTrim($this->data['Link']['title']),
			'content'=>superTrim($this->data['Link']['content']),
			'user_id'=>$this->Auth->user('id'),
			'ip'=>Visitor::ip()
		));
		
		$this->Link->setValidateStep2();	
		
		if ($this->Link->save($this->data,true,array('title','tags','content','category_id','url','blog_id','link_title','link_content','type','user_id','thumb','user_ip'))) {
						
			$this->data['Link']['thumb']=str_replace(array('..',DS), '', $this->data['Link']['thumb']);
			if (file_exists(WWW_ROOT.'img'.DS.'link'.DS.'tmp'.DS.$this->data['Link']['thumb'].'.jpg')){
				@copy( WWW_ROOT.'img'.DS.'link'.DS.'tmp'.DS.$this->data['Link']['thumb'].'.jpg', WWW_ROOT.'img'.DS.'link'.DS.$this->data['Link']['thumb'].'.jpg');
			}  

			try{
				$this->Link->vote($this->Link->id,array(
					'id'=>$this->Auth->user('id'),
					'karma'=>round($this->Auth->user('karma'))
				));
			} catch (ErrorVoteException $e){}
			
			$this->Session->setFlash(__('The link has been saved', true));
			$this->redirect(array('action' => 'view',$this->Link->id));
		}else{
			$errors = $this->Link->invalidFields();
			
			if(isset($errors['url'])){
				$this->Session->setFlash(__('Theres has been a fatal error while submitting your url;'. $errors['url'], true));
				$this->redirect(array('action' => 'add'));
			}
			
			$this->Session->setFlash(__('The link could not be saved. Correct the error fields and try again.', true));
		}
	}
}
?>